#!/bin/bash

set -e

echo "==> [1/8] 禁用 swap..."
sudo swapoff -a
sudo sed -i '/ swap / s/^/#/' /etc/fstab

echo "==> [2/8] 内核模块配置..."
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF

sudo modprobe overlay
sudo modprobe br_netfilter

cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-ip6tables=1
net.ipv4.ip_forward=1
EOF
sudo sysctl --system

echo "==> [3/8] 安装 containerd..."
sudo apt update && sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release containerd

sudo mkdir -p /etc/containerd
containerd config default | sudo tee /etc/containerd/config.toml > /dev/null
sudo sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
sudo systemctl restart containerd
sudo systemctl enable containerd

echo "==> [4/8] 添加 Kubernetes 阿里云源..."
curl -fsSL https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add -
cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list
deb https://mirrors.aliyun.com/kubernetes/apt kubernetes-xenial main
EOF
sudo apt update

echo "==> [5/8] 安装 kubelet kubeadm kubectl..."
KUBE_VERSION=1.29.0-00
sudo apt install -y kubelet=$KUBE_VERSION kubeadm=$KUBE_VERSION kubectl=$KUBE_VERSION
sudo apt-mark hold kubelet kubeadm kubectl

echo "==> [6/8] kubeadm 初始化..."
POD_CIDR="10.244.0.0/16"
sudo kubeadm init --pod-network-cidr=${POD_CIDR} --kubernetes-version=v1.29.0

echo "==> [7/8] 配置 kubectl 环境..."
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

echo "==> [8/8] 安装 Flannel 网络插件..."
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml

echo "🎉 Kubernetes 安装完成！使用命令 kubectl get nodes 检查状态。"
